package net.biancheng.framework.web.service;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import net.biancheng.common.constant.CommonConstant;
import net.biancheng.common.core.redis.RedisCache;
import net.biancheng.common.model.LoginUser;
import net.biancheng.common.utils.IdUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author: lb
 * @date: 2023/8/1 16:36
 * @desc: JWT工具类
 **/
@Component
public class JwtTokenService {

    // 令牌自定义标识
    @Value("${jwt.header}")
    private String header;

    // 令牌秘钥
    @Value("${jwt.secret}")
    private String secret;

    // 令牌有效期（默认30分钟）
    @Value("${jwt.expireTime}")
    private int expireTime;

    protected static final long MILLIS_SECOND = 1000;//一秒

    protected static final long MILLIS_MINUTE = 60 * MILLIS_SECOND;//一分钟

    private static final Long MILLIS_MINUTE_TEN = 20 * 60 * 1000L;//20分钟

    @Autowired
    private RedisCache redisUtils;


    /**
     * 根据请求获取登录用户信息
     * @param request
     * @return
     */
    public LoginUser getLoginUser(HttpServletRequest request){
        String token = getToken(request);
        if(StringUtils.isNotEmpty(token)){
            try {
                //获取创建token保留值
                Claims claims = parseToken(token);
                String uuid = (String)claims.get(CommonConstant.LOGIN_USER_KEY);
                String tokenKey = getTokenKey(uuid);
                LoginUser user = redisUtils.getCacheObject(tokenKey);
                return user;
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * 设置登录用户身份信息
     * @param loginUser
     */
    public void setLoginUser(LoginUser loginUser){
        if (loginUser != null && StringUtils.isNotEmpty(loginUser.getUserKey()))
        {
            refreshToken(loginUser);
        }
    }

    /**
     * 删除用户身份信息
     */
    public void delLoginUser(String userKey)
    {
        if (StringUtils.isNotEmpty(userKey))
        {
            String tokenKey = getTokenKey(userKey);
            redisUtils.deleteObject(tokenKey);
        }
    }

    /**
     * 创建令牌token
     *
     * @param loginUser 用户信息
     * @return 令牌
     */
    public String createToken(LoginUser loginUser)
    {
        String uuid = IdUtils.fastUUID();
        loginUser.setUserKey(uuid);
        refreshToken(loginUser);

        Map<String, Object> claims = new HashMap<>();
        claims.put(CommonConstant.LOGIN_USER_KEY, uuid);
        String token = Jwts.builder()
                .setClaims(claims)
                .signWith(SignatureAlgorithm.HS512, secret).compact();
        return token;
    }

    /**
     * 验证令牌有效期，相差不足20分钟，自动刷新缓存
     *
     * @param loginUser
     * @return 令牌
     */
    public void verifyToken(LoginUser loginUser)
    {
        long expireTime = loginUser.getExpireTime();
        long currentTime = System.currentTimeMillis();
        if (expireTime - currentTime <= MILLIS_MINUTE_TEN)
        {
            refreshToken(loginUser);
        }
    }

    /**
     * 刷新令牌有效期
     *
     * @param loginUser 登录信息
     */
    public void refreshToken(LoginUser loginUser)
    {
        loginUser.setLoginTime(System.currentTimeMillis());
        loginUser.setExpireTime(loginUser.getLoginTime() + expireTime * MILLIS_MINUTE);
        // 根据uuid将loginUser缓存
        String tokenKey = getTokenKey(loginUser.getUserKey());
        redisUtils.setCacheObject(tokenKey, loginUser, expireTime, TimeUnit.MINUTES);
    }

    /**
     * 从token中获取数据声明（创建token时的保留值）
     * @param token
     * @return
     */
    private Claims parseToken(String token){
        return Jwts.parser()
                .setSigningKey(secret)
                .parseClaimsJws(token)
                .getBody();
    }

    /**
     * 获取请求token
     * @param request
     * @return
     */
    private String getToken(HttpServletRequest request){
        String token = request.getHeader(header);
        if (StringUtils.isNotEmpty(token) && token.startsWith(CommonConstant.TOKEN_PREFIX)){
            token = token.replace(CommonConstant.TOKEN_PREFIX, "");
        }
        return token;
    }

    /**
     * 获取token缓存到redis的key
     * @param uuid
     * @return
     */
    private String getTokenKey(String uuid)
    {
        return CommonConstant.LOGIN_TOKEN_KEY + uuid;
    }

}
